import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from UAS.data_utils import (
    load_results_file,
    get_iteration_number
)

class VisualizationPanel(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        # 设置matplotlib支持中文显示
        plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
        plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
        self.create_widgets()
        self.iteration_data = []
        self.score_data = []
        self.time_data = []
        

    def create_widgets(self):
        # Visualization frame
        vis_frame = ttk.Frame(self)
        self.figure = Figure(figsize=(10, 6))
        self.canvas = FigureCanvasTkAgg(self.figure, master=vis_frame)
        self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        
        # 创建主y轴并设置数值格式
        self.ax1 = self.figure.add_subplot(111)
        self.ax1.yaxis.set_major_formatter('{x:.1f}')  # 显示一位小数
        # 确保标签显示在左侧
        self.ax1.yaxis.set_label_position('left')
        self.ax1.yaxis.tick_left()
        
        # 创建次y轴并设置数值格式
        self.ax2 = self.ax1.twinx()
        self.ax2.yaxis.set_major_formatter('{x:.0f}')  # 只显示整数
        # 确保标签显示在右侧
        self.ax2.yaxis.set_label_position('right')
        self.ax2.yaxis.tick_right()
        
        vis_frame.pack(fill=tk.BOTH, expand=True)

    def update_visualization_data(self, filename):
        """从json文件更新可视化数据"""
        # 如果是第一次更新，清空旧数据
        if filename == 'results_0.json':
            self.iteration_data = []
            self.score_data = []
            self.time_data = []
            
        try:
            data = load_results_file(filename)
        except FileError as e:
            print(f"File error: {e}")
            return
        except DataError as e:
            print(f"Data error: {e}") 
            return
            
        x_value = get_iteration_number(filename)
            
        # 更新数据
        self.iteration_data.append(x_value)
        self.score_data.append(data['results'][0]['total_profit'])
        self.time_data.append(data['results'][0]['total_time'])
            
        self.update_visualization()
        
    def update_visualization(self):
        """更新图表"""
        self.ax1.clear()
        self.ax2.clear()
        # 重新设置右侧轴的位置
        self.ax2.yaxis.set_label_position('right')
        self.ax2.yaxis.tick_right()
        
        if self.iteration_data and self.score_data:
            # 在左侧y轴绘制总时间
            self.ax1.plot(self.iteration_data, self.time_data,
                        label='总用时', color='#FF6F61',
                        marker='x', linestyle='--', linewidth=2)
            
            if self.score_data and len(self.score_data) == len(self.iteration_data):
                # 在右侧y轴绘制总积分
                self.ax2.plot(self.iteration_data, self.score_data,
                           label='最优积分', color='#6B5B95',
                           marker='o', linestyle='--')
            
            # 设置x轴刻度为0,5,10,15...
            max_iter = max(self.iteration_data)
            self.ax1.set_xticks(range(0, max_iter + 1, 5))
            self.ax1.set_xlabel('迭代次数', fontsize=10)
            self.ax1.set_ylabel('总用时（分钟）', fontsize=10)
            self.ax2.set_ylabel('最优积分', fontsize=10)
            
            # 合并图例
            lines1, labels1 = self.ax1.get_legend_handles_labels()
            lines2, labels2 = self.ax2.get_legend_handles_labels()
            self.ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')
            
            self.canvas.draw()
